<!--
  描述：拖放地图组件，默认尺寸是 100% * 400
  lat: 纬度  lng: 经度
  接收属性参数：
    markers: [{ lng: 120.287631, lat: 29.156497 }] // 默认标记点
    center: { lng: 120.287631, lat: 29.156497 } // 居中位置点
  自定义事件：
    drag: 拖放完成事件
    on-click: 点击获取经纬度
  示例：
    <gao-de-map @drag="dragMap" @on-click="onClick" :markers="markers" :center="center"></gao-de-map>
-->
<template>
  <div class="m-map" :style="{width: width, height: height}">
    <div class="search" v-if="placeSearch">
      <el-input v-model="searchKey" placeholder="请输入关键字" @keyup.enter.native="handleSearch" suffix-icon="el-icon-search"/>
      <div id="js-result" v-show="searchKey" class="result"></div>
    </div>
    <div class="lng-lat">
      <el-input v-model="curLngLat" readonly>
        <template slot="prepend">经纬度</template>
      </el-input>
    </div>
    <div id="js-container" class="map">
      <div class="loading" v-loading="loading"
           element-loading-text="正在加载数据"
           element-loading-spinner="el-icon-loading"></div>
    </div>
  </div>
</template>

<script>
  import remoteLoad from '@/utils/remoteLoad.js'
  export default {
    props: {
      center: {
        type: Object,
        default: ()=>{
          return this.$config.lngLat

        }      },
      markers: {
        type: Array,
        default: ()=>{
          return []
        }
      },
      type: {
        type: String,
        default: 'click'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '400px'
      }
    },
    data () {
      return {
        loading: true,
        searchKey: '',
        placeSearch: null,
        dragStatus: false,
        AMapUI: null,
        AMap: null,
        marker: {},
        curLngLat: ''
      }
    },
    watch: {
      searchKey () {
        if (this.searchKey === '') {
          this.placeSearch.clear()
        }
      },
      center: {
        deep: true,
        handler(val) {
          this.initMap()
        }
      },
      markers: {
        deep: true,
        handler(val) {
          this.initMap()
          if(val.length){
            let lnglat = val[0]
            this.curLngLat = `${lnglat.lng}, ${lnglat.lat}`
          }
        }
      }
    },
    computed: {
      centerLngLat(){
        let len = Object.keys(this.center).length
        if(len == 0){
          return this.$config.lngLat
        } else {
          return this.center
        }
      }
    },
    async created () {
      // 已载入高德地图API，则直接初始化地图
      if (window.AMap && window.AMapUI) {
        this.initMap()
        // 未载入高德地图API，则先载入API再初始化
      } else {
        await remoteLoad(`//webapi.amap.com/maps?v=1.4.16&key=${this.$config.mapKey}`)
        await remoteLoad('//webapi.amap.com/ui/1.0/main.js')
        this.$nextTick(()=>{
          this.initMap()
        })
      }
      if(this.markers.length){
        let lnglat = this.markers[0]
        this.curLngLat = `${lnglat.lng}, ${lnglat.lat}`
      }
    },
    mounted() {
    },
    methods: {
      // 搜索
      handleSearch () {
        if (this.searchKey) {
          this.placeSearch.search(this.searchKey)
        }
      },
      // 实例化地图
      initMap () {
        // 加载PositionPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
        let AMapUI = this.AMapUI = window.AMapUI
        let AMap = this.AMap = window.AMap
        AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
          let mapConfig = {
            zooms: [8, 18],
            zoom: 15,
            cityName: this.$config.mapCityName
          }
          if (this.centerLngLat.lat && this.centerLngLat.lng) {
            mapConfig.center = [this.centerLngLat.lng, this.centerLngLat.lat]
          }
          let map = this.map = new AMap.Map('js-container', mapConfig)

          map.setDefaultCursor('pointer') // 鼠标样式

          // 加载地图搜索插件
          AMap.service('AMap.PlaceSearch', () => {
            this.placeSearch = new AMap.PlaceSearch({
              pageSize: 5, // 每页显示多少行
              pageIndex: 1, // 显示的下标从那个开始
              citylimit: true, // 类别，可以以|后面加其他类
              city: this.$config.mapCityName, // 城市
              map: map, // 显示地图
              panel: 'js-result' // 服务显示的面板
            })
          })
          // 启用工具条
          AMap.plugin(['AMap.ToolBar'], function () {
            map.addControl(new AMap.ToolBar({
              position: 'RB'
            }))
          })

          // 回显默认点位 markers
          if(this.markers.length){
            this.marker = this.markers.map(item => {
              return new this.AMap.Marker({
                position: [item.lng, item.lat],
                map: map // 依赖地图对象
              })
            })
            map.add(this.marker)
          }

          if(this.type === 'click'){
            // 点击添加marker 获取经纬度
            AMap.event.addListener(map,'click', e => { //添加点击事件,传入对象名，事件名，回调函数
              const { lnglat } = e
              if (this.marker) {
                map.remove(this.marker) // 移除marker
              }
              this.marker = new AMap.Marker({
                position: [lnglat.lng, lnglat.lat],
                map: map // 依赖地图对象
              })
              map.add(this.marker)
              this.$emit('on-click', e)
              this.curLngLat = `${lnglat.lng}, ${lnglat.lat}`
            })
          }

          if(this.type === 'drag'){
            // 创建地图拖拽
            let positionPicker = new PositionPicker({
              mode: 'dragMarker', // 设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
              map: map // 依赖地图对象
            })
            // 拖拽完成发送自定义 drag 事件
            positionPicker.on('success', positionResult => {
              // 过滤掉初始化地图后的第一次默认拖放
              if (!this.dragStatus) {
                this.dragStatus = true
              } else {
                this.$emit('drag', positionResult)
                const { position } = positionResult
                this.curLngLat = `${position.lng}, ${position.lat}`
              }
            })
            // 启动拖放
            positionPicker.start()
          }

        })
        this.loading = false
      },

    }

  }
</script>

<style scoped lang="css">
  /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
  ::-webkit-scrollbar {
    width: 7px;
    height: 7px;
    background-color: #F5F5F5;
  }
  /*定义滚动条轨道 内阴影+圆角*/
  ::-webkit-scrollbar-track {
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    background-color: #F5F5F5;
  }
  /*定义滑块 内阴影+圆角*/
  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
    background-color: #c8c8c8;
  }
  .m-map{ min-width: 500px; min-height: 300px; position: relative; }
  .m-map .map{ width: 100%; height: 100%; display: flex; align-items: center; justify-content: space-between }
  .m-map .map .loading {width: 100%; height: 100%;}
  .m-map .search{ position: absolute; top: 10px; left: 10px; width: 285px; z-index: 1; }
  .m-map .result{ max-height: 300px; overflow: auto; margin-top: 10px; }
  .m-map .lng-lat {position: absolute; top: 10px; right: 10px; width: 285px; z-index: 1; }
</style>
